from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
# urllib python内置的标准模块，用于发送http请求，类似vue里面的axios
from urllib.parse import urlencode
from urllib.request import urlopen
import json
class CaptchaAPIView(APIView):
    """验证码"""
    def get(self,request):
        """接受客户端提交的验证码相关信息"""
        params = {
            "aid": settings.TENCENT_CAPTCHA.get("APPID"),
            "AppSecretKey": settings.TENCENT_CAPTCHA.get("App_Secret_Key"),
            "Ticket": request.query_params.get("ticket"),
            "Randstr": request.query_params.get("randstr"),
            # request._request表示获取django框架的request对象
            # request._request.META获取本次客户端的请求头
            "UserIP": request._request.META.get("REMOTE_ADDR")
        }
        # 把字典数据转换成地址栏的查询字符串格式
        # aid=xxx&AppSecretKey=xxx&xxxxx
        params = urlencode(params)
        url = settings.TENCENT_CAPTCHA.get("GATEWAY")
        # 发送http的get请求
        # urlopen(url=请求地址，data=请求体数据)
        # 如果get请求，只需要填写参数1
        # 如果post请求，则需要填写参数1和参数2，其中参数2的格式为字典格式
        # urlopen是一个资源对象
        f = urlopen("%s?%s" % (url, params))
        # https://ssl.captcha.qq.com/ticket/verify?aid=xxx&AppSecretKey=xxx&xxxxx

        # f.read() 读取响应信息
        content = f.read()
        res = json.loads(content)
        if int(res.get("response")) == 1:
            # 验证成功
            return Response({"detail":1})
        else:
            # 验证失败
            return Response({"detail":0}, status=status.HTTP_400_BAD_REQUEST)

from rest_framework.generics import CreateAPIView
from .models import User
from .serializers import UserSerializer
class UserAPIView(CreateAPIView):

    queryset = User.objects.all()
    serializer_class = UserSerializer

import random,json  #生成随机验证码用模块
from django_redis import get_redis_connection  #redis模块
from ronglian_sms_sdk import SmsSDK  #云容联验证码模块
from renranapi.settings import constants #配置文件
import logging #日志模块
logger = logging.getLogger("django")   #选择日志记录方式
from mycelery.sms.tasks import send_sms
class SMSAPIView(APIView):
    '''短信发送模块'''
    def get(self,request,phone):
        '''接受前段数据并发送短信验证码同时存入redis数据库'''
        #初始化redis数据库
        redis_conn = get_redis_connection("sms_code")
        #获取字段用于判断是否在规定时间内发送过验证码
        ret =  redis_conn.get("interval_%s"%phone)
        if ret is not None:
            return Response({"detail":"发送太频繁了"})
        #生成随机验证码
        sms_code = "%06d"%(random.randint(1,999999))
        #为了数据安全我们使用事务
        #实例化redis管道
        pipe = redis_conn.pipeline()
        #新增时限字段包括验证码有效期和发送间隔控制
        pipe.setex("sms_%s"%phone,constants.SMS_EXPIRT_TIME ,sms_code)
        pipe.setex("interval_%s"%phone,constants.SMS_INTERVAL_TIME,1)
        #执行管道内任务
        pipe.execute()
        #根据配置文件对接短信平台接口以及发送短信内容
        send_sms.delay(phone=phone,sms_code=sms_code)

        return Response({"detail": "短信已发送!请留意您的手机短信!"})

class CheckPhone(APIView):
    '''检测手机号是否重复 '''
    def get(self,request,phone):

        try:
            user = User.objects.get(phone=phone)
            return Response({"detail":"手机号已经存在了"})
        except :
            return Response("ok")